package net.alan.modules.controller;

import net.alan.common.constants.ELogType;
import net.alan.common.utils.AddressUtils;
import net.alan.modules.aspect.NotAuthorize;
import net.alan.modules.bean.UserLog;
import net.alan.modules.cache.WebContextUtil;
import net.alan.modules.handle.BaseExecption;
import net.alan.modules.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Author 李岩飞
 * Email eliyanfei@126.com
 * 2017/11/21
 */
@Controller
@RequestMapping(value = "base")
public class BaseController {
    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);
    public HttpServletRequest request;
    public HttpServletResponse response;
    public HttpSession session;

    @Autowired
    private IUserService logService;

    /**
     * 每次执行请求前都会先执行它再执行请求
     *
     * @param request
     * @param response
     */
    @NotAuthorize
    @ModelAttribute
    public void setServletApi(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }
    @NotAuthorize
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
    }

    /**
     * 记录用户日志
     * @param logType
     */
    protected void addLog(ELogType logType,HttpServletRequest request) {
        try {
            String ipAddr = AddressUtils.getIpAddr(request);
            //保存用户的设备信息
            UserLog log = new UserLog();
            log.setIp(ipAddr);
            log.setLogType(logType.name());
            log.setUserId(WebContextUtil.getCurrentUser().getUser().getId());
            log.setDetail(logType.getName());
            this.logService.save(UserLog.class,log);
        } catch (Exception e) {
        } catch (BaseExecption baseExecption) {
            baseExecption.printStackTrace();
        }
    }

    @RequestMapping(value = "error", method = RequestMethod.GET)
    public String norole() throws Exception {
        return "error/error";
    }
}
